import { PropType, defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import {
  AppFuncCommand,
  IAppMenuController,
  PanelItemController,
} from '@ibiz-template/runtime';
import { IPanelRawItem } from '@ibiz/model-core';
import './user-action.scss';
import { showTitle } from '@ibiz-template/core';

export const UserAction = defineComponent({
  name: 'IBizUserAction',
  props: {
    modelData: {
      type: Object as PropType<IPanelRawItem>,
      required: true,
    },
    controller: {
      type: Object as PropType<PanelItemController>,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('user-action');
    const c = props.controller;

    // 图片配置
    const imgConfig: IData = {
      SETTING: { imagePath: 'svg/setting.svg' },
      HELPER: { imagePath: 'svg/helper.svg' },
      CUSTOM: { imagePath: 'svg/custom-workbench.svg' },
    };

    let sysImage = props.modelData.sysImage;

    if (!sysImage && props.modelData && props.modelData.rawItem) {
      const predefinedType: string | undefined =
        props.modelData.rawItem.predefinedType;
      if (predefinedType) {
        sysImage = imgConfig[predefinedType];
      }
    }

    // 寻找对应的菜单项并打开对应应用功能
    const onClick = async (event: Event) => {
      const e = { ...event };
      e.target = event.currentTarget;
      const id = props.modelData.id;
      const menuC = c.panel.view.getController('appmenu') as IAppMenuController;
      if (menuC) {
        const targetMenu = menuC.allAppMenuItems.find((item: IData) => {
          return item.id === id;
        });
        if (targetMenu) {
          // 映射菜单项无权限触发不生效
          if (targetMenu.accessKey) {
            const app = await ibiz.hub.getApp(c.panel.context.srfappid);
            const permitted = app.authority.calcByResCode(targetMenu.accessKey);
            if (!permitted) return;
          }
          const tempContext = c.panel.context.clone();
          const tempParam = c.panel.params;
          tempContext.srfappid = targetMenu.appId || ibiz.env.appId;

          await ibiz.commands.execute(
            AppFuncCommand.TAG,
            targetMenu.appFuncId,
            tempContext,
            tempParam,
            { event: e },
          );
        }
      }
    };

    return {
      ns,
      c,
      sysImage,
      onClick,
    };
  },
  render() {
    return (
      <div class={this.ns.b()} title={showTitle(this.modelData.caption)}>
        <i-biz-icon
          class={[this.ns.e('image')]}
          icon={this.sysImage}
          onClick={(event: Event) => this.onClick(event)}
        ></i-biz-icon>
      </div>
    );
  },
});
